package br.puc.paa.graph.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import br.puc.paa.graph.model.Aresta;
import br.puc.paa.graph.model.Grafo;
import br.puc.paa.graph.model.Vertice;

public class STPFileUtil {

	public static Grafo getGrafo(File arquivoSTP) throws IOException {

		Grafo grafo = new Grafo();

		Map<String, Vertice> verticePeloRotulo = new HashMap<String, Vertice>();

		String line;
		boolean readEdges = false;
		
		BufferedReader bufferedReader = new BufferedReader(new FileReader(arquivoSTP));
		
		while ((line = bufferedReader.readLine()) != null) {

			if (line.toLowerCase().contains("section graph")) {
				readEdges = true;
				continue;
			}

			if (readEdges) {
				if (line.toLowerCase().contains("nodes")) {
					continue;
				}
				if (line.toLowerCase().contains("edges")) {
					continue;
				}
				if (line.toLowerCase().contains("end")) {
					readEdges = false;
					break; // nao precisa ler mais nada
				}

				//The three values are Tail-Node (edge[1]), Head-Node (edge[2]) and Weight (edge[3]) - http://steinlib.zib.de/format.php
				
				String[] edge = line.split(" ");
				
				String rolutoVerticeOrigem = edge[1];
				String rolutoVerticeDestino = edge[2];
				
				if(verticePeloRotulo.get(rolutoVerticeOrigem) == null){
					verticePeloRotulo.put(rolutoVerticeOrigem, new Vertice(rolutoVerticeOrigem));
				}
				
				if(verticePeloRotulo.get(rolutoVerticeDestino) == null){
					verticePeloRotulo.put(rolutoVerticeDestino, new Vertice(rolutoVerticeDestino));
				}
				
				Vertice verticeOrigem = verticePeloRotulo.get(rolutoVerticeOrigem);
				Vertice verticeDestino = verticePeloRotulo.get(rolutoVerticeDestino);

				int custo = Integer.parseInt(edge[3]);
				Aresta aresta = new Aresta(verticeOrigem, verticeDestino, custo);
				
				verticeOrigem.addArestaDeSaida(aresta);
				verticeDestino.addArestaDeEntrada(aresta);

			}
		}
		
		bufferedReader.close();
		
		Set<String> keySet = verticePeloRotulo.keySet();
		
		for(String rotulo : keySet){
			Vertice vertice = verticePeloRotulo.get(rotulo);
			grafo.addVertice(vertice);
		}

		return grafo;
	}

}